import fetch from 'isomorphic-fetch';
import {getToken,getUserId} from './token'
import $ from 'jquery'

function parseJSON(response) {
	return response.json();
}

function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response;
	}

	const error = new Error(response.statusText);
	error.response = response;
	throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
	if(!url) return;
	if(!options) options = {}
	if (!options.headers) {
		options.headers = {
			'Content-Type': 'application/json'
		}
	}
  let token = getToken()
	console.log("token="+token)
	let userId = getUserId()
  if (token) {
    url = url.indexOf('?') > -1 ? url + `&userId=${userId}&token=${token}`: url + `?userId=${userId}&token=${token}`
  }
  else
    console.warn('没有token')
	return $.ajax(url,options)
	.then((data,status,xhr) => {

		const parsedData = typeof(data) === 'object' ? data : JSON.parse(data)
		let timestamp
		if(xhr.getResponseHeader("date")){
			timestamp = new Date(xhr.getResponseHeader("date")).getTime();
		}
		return {data:parsedData,ctimestamp:timestamp}
	})
	.catch(err => {
    // if (err.status == 404 && token) {
    //   alert('商品已空')
    // }
    return {err}
  })

	// return fetch(url, options)
	// 	.then(checkStatus)
	// 	.then(parseJSON)
	// 	.then(data => ({data}))
	// 	.catch(err => ({err}));
}
